#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import datetime, requests, json
from random import randint

from  vouchers.models import AliDiscountCoupon, AliDiscountCouponQRCode, AliDiscountCouponLevel
from equity_mall.utils.utils import random_str
from vouchers.utils import AlipayOpen


def get_short_url(url_long):
    host = 'https://dwz.cn'
    path = '/admin/v2/create'
    url = host + path
    method = 'POST'
    content_type = 'application/json'

    # TODO: 设置Token
    token = '0f20b90fa4dcfe5d1a81cf5e6781c976'

    # TODO：设置待创建的长网址
    bodys = {'Url': url_long, 'TermOfValidity': "1-year"}

    # 配置headers
    headers = {'Content-Type': content_type, 'Token': token}

    # 发起请求
    res = requests.post(url=url, data=json.dumps(bodys), headers=headers)
    return json.loads(res.text)


def batch_qrcode():
    activity_level = AliDiscountCouponLevel.objects.filter(activity_id=18261).first()
    for i in range(130000):
        qrcode_data = {}
        identify = random_str()
        check_qrcode = AliDiscountCouponQRCode.objects.filter(identify=identify)
        if check_qrcode:
            continue
        common_url = f'https://api.sutpay.com/customer/applet/?identify={identify}'
        short_url = get_short_url(common_url)
        qrcode_data['identify'] = identify
        try:
            qrcode_data['common_url'] = short_url['ShortUrl']
        except:
            print(short_url)
            continue
        qrcode_data['alidiscountcoupon_level_id'] = activity_level.id
        out_biz_no = f'100003{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        qrcode_data['out_biz_no'] = out_biz_no
        AliDiscountCouponQRCode.objects.create(**qrcode_data)


def batch_qrcode1():
    activity_level = AliDiscountCouponLevel.objects.filter(activity_id=18634).first()
    for i in range(100000):
        qrcode_data = {}
        identify = random_str()
        common_url = f'https://api.sutpay.com/customer/applet/?identify={identify}'
        alipay_obj = AlipayOpen()
        result = json.loads(alipay_obj.sharetoken(common_url))
        qrcode_data['identify'] = identify
        try:
            qrcode_data['common_url'] = result['share_token']
        except:
            print(result)
            continue
        qrcode_data['alidiscountcoupon_level_id'] = activity_level.id
        out_biz_no = f'100003{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        qrcode_data['out_biz_no'] = out_biz_no
        AliDiscountCouponQRCode.objects.create(**qrcode_data)


if __name__ == '__main__':
    pass
    batch_qrcode1()

